package com.hnchances.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hnchances.common.vo.Code;
import com.hnchances.common.vo.ResultVo;
import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class CheckToKenInterceptor implements HandlerInterceptor {
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // token设置在headers时
        // 当前端自定义header时 浏览器有预检机制发送的请求方法为  OPTIONS
        String method = request.getMethod();
        if (method.equals("OPTIONS")) return true;
        String token = request.getHeader("token");
        // token作为参数传递时
        // String token = request.getParameter("token");
        if (token == null) {
            // 提示请先登录
            ResultVo resultVo = ResultVo.error().message("请先登录").code(Code.LOGIN_ERROR);
            doResponse(response, resultVo);
        }
        try {
            // 验证token
            JwtParser parser = Jwts.parser();
            parser.setSigningKey("zhangxueyang");
            Jws<Claims> claimsJws = parser.parseClaimsJws(token);
            Integer id = (Integer) claimsJws.getBody().get("id");
            return true;
        } catch (ExpiredJwtException e) {
            ResultVo resultVo = ResultVo.error().code(Code.LOGIN_ERROR).message("登录过期，请重新登陆");
            doResponse(response, resultVo);
        } catch (UnsupportedJwtException e) {
            ResultVo resultVo = ResultVo.error().message("Token不合法，请重新登陆");
            doResponse(response, resultVo);
        } catch (Exception e) {
            ResultVo resultVo = ResultVo.error().code(Code.LOGIN_ERROR).message("请重新登录");
            doResponse(response, resultVo);
        }
        return false;
}

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }


    private void doResponse(HttpServletResponse response, ResultVo resultVo) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        PrintWriter writer = response.getWriter();
        String res = new ObjectMapper().writeValueAsString(resultVo);
        writer.println(res);
        writer.flush();
        writer.close();
    }
}
